package com.hmdp.utils;

import cn.hutool.core.date.LocalDateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author zkx
 */
@Component
public class RedisIdWorker {

    //开始时间2022-01-01-00:00:00
    private static final long BEGIN_TIME = 1640995200L;
    //序列号的长度
    private  static  final int BITS_LENGTH = 32;

    public RedisIdWorker(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    //
    private StringRedisTemplate redisTemplate;

    /**
     * 返回long类型的key,全局id唯一生成
     *
     */
    public long workId(String prefix){

        //第一步，得到当前时间的秒数
        LocalDateTime now = LocalDateTime.now();
        long nowTime = now.toEpochSecond(ZoneOffset.UTC);
        long endTime = nowTime - BEGIN_TIME;
        //得到年月日
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //第二步，创建key;
        long increment = redisTemplate.opsForValue().increment("icr:" + prefix + ":" + date);
        //拼接返回，由于long不能直接拼接
        //这里拥戴位运算，将endTime往左移动32，然后将于increment去反
        return endTime << BITS_LENGTH  | increment;
    }

}
